package com.wunu.smartlock1.activity

import android.Manifest
import android.bluetooth.BluetoothGatt
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.Button
import com.clj.fastble.BleManager
import com.clj.fastble.callback.BleGattCallback
import com.clj.fastble.callback.BleNotifyCallback
import com.clj.fastble.callback.BleScanCallback
import com.clj.fastble.callback.BleWriteCallback
import com.clj.fastble.data.BleDevice
import com.clj.fastble.exception.BleException
import com.wunu.smartlock1.R
import com.wunu.smartlock1.adapter.ScanListAdapter
import com.wunu.smartlock1.bluetooth.WunuBlueManager
import com.wunu.smartlock1.bluetooth.command.CheckBindCommand
import com.wunu.smartlock1.util.BlueUtil
import com.wunu.smartlock1.util.CommonUtil

/**
 * Created by peiwei on 2018/4/21.
 */
class ScanListActivity : AppCompatActivity() {
    private var devices = ArrayList<BleDevice>()
    private val SERVICE_UUID: String = "F8C00001-159F-11E6-92F5-0002A5D5C51B"
    private val NOTIFITY_UUID: String = "F8C00003-159F-11E6-92F5-0002A5D5C51B"
    private val WRITE_UUID: String = "F8C00002-159F-11E6-92F5-0002A5D5C51B"


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.smartlock_scan_activity)
        val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
        //设置布局
        val layoutManager = LinearLayoutManager(this)
        recyclerView.layoutManager = layoutManager
        //添加事件
        addListener()
    }
    private fun addListener() {
        val scanButton = findViewById<Button>(R.id.scan_peripheral_button)
        scanButton.setOnClickListener {
            scanButton.isSelected = !scanButton.isSelected
            if (scanButton.isSelected) {
                checkBluetoothPermission()
            } else {
                scanButton.text = "扫描设备"
                stopScan()
            }
        }
    }
    public fun startScan() {
        BlueUtil.scanState = false;
        BleManager.getInstance().scan(object : BleScanCallback() {
            val scanButton = findViewById<Button>(R.id.scan_peripheral_button)
            override fun onScanFinished(scanResultList: MutableList<BleDevice>?) {
                System.out.println("💣 scanned count = " + scanResultList?.count() + "💣")
                scanButton.text = "扫描设备"
                BlueUtil.devices = devices;
                BlueUtil.scanState = true;
            }

            override fun onScanStarted(success: Boolean) {
                System.out.println("💣 start scan " + success + "💣")
                scanButton.text = "正在扫描..."
            }

            override fun onScanning(result: BleDevice?) {
                if(result == null)return
                System.out.println("💣" + result.name+"\t"+result.mac + "💣")
                var index = -1
                for (i in 0 until devices.size) {
                    if (devices[i].mac.equals(result.mac)) {
                        System.out.println("两个蓝牙mac一样!"+devices[i].mac+"\t"+result.mac);
                        index = i
                    }
                }
                System.out.println(""+index+"移除前:"+devices.size);
                if (index >= 0) {
                    devices.removeAt(index)
                }
                System.out.println("移除后:"+devices.size);
                //只显示以WSL_开头的蓝牙设备
                if(result.getName() !=null && result.getName().startsWith("WSL_")){
                    devices.add(result);
                }
               /* if (!devices.contains(result)) {
                    devices.add(result!!)
                } else {
                    val index = devices.indexOf(result!!)
                    devices.removeAt(index)
                    devices.add(index, result)
                }*/

                //设置adapter
                val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
                val adapter = ScanListAdapter(devices, object : ScanListAdapter.OnItemClickListener {
                    override fun onItemClick(view: View, position: Int) {
                        CommonUtil.device = devices[position]
                        intent.putExtra("param", devices[position])
                        System.out.println("点击了第"+position+"蓝牙:"+devices[position].mac+"\t"+devices[position].key+"\t"+devices[position].rssi+"\t"+devices[position].scanRecord+"\t"+devices[position].device)
                        startActivity(intent.setClass(this@ScanListActivity, LockBindActivity::class.java))
                    }
                })
                adapter.notifyDataSetChanged()
                recyclerView.adapter = adapter

            }

            override fun onLeScan(bleDevice: BleDevice?) {

            }
        })
    }

    private fun notifyMessage(bleDevice: BleDevice) {
        BleManager.getInstance().notify(bleDevice, SERVICE_UUID, NOTIFITY_UUID, object : BleNotifyCallback() {
            override fun onNotifySuccess() {
                // 打开通知操作成功
                System.out.println("打开通知成功")
                // 写数据
                writeMessage(bleDevice, CheckBindCommand().payload())
            }

            override fun onNotifyFailure(exception: BleException?) {
                // 打开操作通知失败
                System.out.println("打开通知失败")
            }

            override fun onCharacteristicChanged(data: ByteArray?) {
                // 打开通知接受数据
                System.out.println("接受到的数据： " + bytesToHexString(data!!))
            }
        })
    }

    private fun writeMessage(bleDevice: BleDevice, data: ByteArray) {
        System.out.println("写入的数据: " + bytesToHexString(data))
        BleManager.getInstance().write(bleDevice, SERVICE_UUID, WRITE_UUID, data, object : BleWriteCallback() {
            override fun onWriteFailure(exception: BleException?) {
                //数据写入失败
                System.out.println("写入数据失败 error = " + exception.toString())
            }

            override fun onWriteSuccess(current: Int, total: Int, justWrite: ByteArray?) {
                //数据写入成功
                System.out.println("写入数据成功: data = " + bytesToHexString(justWrite!!))

            }
        })
    }

    private fun stopScan() {
        BleManager.getInstance().cancelScan()
    }

    private fun checkBluetoothPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN),1000)
            } else {
                startScan()
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        if (requestCode == 1000) {
            startScan()
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }
    private fun bytesToHexString(byteArray: ByteArray): String {
        var hs = ""
        var stmp = ""
        for (i in 0..byteArray.count()-1) {
            stmp = Integer.toHexString(byteArray[i].toInt().and(0xff))
            if (stmp.length < 2) {
                hs += '0'
            }
            hs += stmp.toUpperCase()
        }
        return hs.toString()
    }
}